<template>
    <div id="SelectTopic">
        <el-dialog
            title="选择考题"
            v-model="selectDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
        >
            <div>
                <el-divider content-position="left">题库数据</el-divider>
                <el-form class="box-f" ref="queryForm" :inline="true">
                    <el-form-item label="培训计划：">
                        <el-input v-model="v_CourseName" disabled readonly />
                    </el-form-item>
                    <el-form-item label="考题类型：">
                        <el-select 
                            v-model="transferVal" 
                            filterable 
                            class="m-2" 
                            placeholder="请选择考题类型" 
                            @change="acquireChange"
                            popper-class="set-select"
                            :popper-append-to-body="false"
                        >
                            <el-option
                                v-for="item in responsiblePle"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <!-- <el-button @click='searchClick' icon="ele-Search" type="primary"> 查询 </el-button> -->
                        <!-- <el-button  @click="testPaperClick(list[1])" icon="ele-Refresh"> 查看已选题目 </el-button> -->
                    </el-form-item>
                </el-form>
                <el-table 
                    ref="multipleTableRef" 
                    :data="listData"
                    class="table-s chose-tab" 
                    v-loading="loading" 
                    style="width: 100%"
                    border
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column type="selection" width="55" />
                    <el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
                    <el-table-column min-width="200" :show-overflow-tooltip="true" label="考题类型"  align="center">
                        <template #default="scope">
                            <span v-if="scope.row.n_Type === 0" style="color: #409EFF;">{{scope.row.v_TypeName}}</span>
                            <span v-if="scope.row.n_Type === 1" style="color: #67C23A;">{{scope.row.v_TypeName}}</span>
                            <span v-if="scope.row.n_Type === 2" style="color: #E6A23C;">{{scope.row.v_TypeName}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="160" :show-overflow-tooltip="true" prop="n_Score" label="单题分数"  align="center" />
                    <el-table-column min-width="160" :show-overflow-tooltip="true" prop="n_Sort" label="排序号"  align="center" />
                    <el-table-column min-width="160" :show-overflow-tooltip="true" prop="v_Topic" label="题目"  align="center" />
                    <el-table-column min-width="160" :show-overflow-tooltip="true" label="详情数据"  align="center">
                        <template #default="scope">
                            <el-popover placement="left" :width="600" trigger="click">
                                <template #reference>
                                    <el-button text type="primary">查看</el-button>
                                </template>
                                <el-table border :data="scope.row.options">
                                    <el-table-column min-width="60" prop="v_Option" :show-overflow-tooltip="true" label="选项"  align="center">
                                        <template #default="scoped">
                                            <span v-if="scoped.row.v_Option">{{scoped.row.v_Option}}</span>
                                            <span v-else>-</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column min-width="160" prop="v_Content" :show-overflow-tooltip="true" label="内容"  align="center" />
                                    <el-table-column min-width="100" :show-overflow-tooltip="true" label="是否为正确答案"  align="center">
                                        <template #default="scoped">
                                            <span v-if="scoped.row.isTrue" style="color: #67C23A;">是</span>
                                            <span v-else style="color: #E6A23C;">否</span>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-popover>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="height: 30px;margin-top: 20px;" class="hr-flex-start">
                    <el-pagination
                        v-model:currentPage="pageNo"
                        v-model:page-size="pageSize"
                        :total="totalRows"
                        :page-sizes="[20, 50, 100]"
                        small
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        layout="total, sizes, prev, pager, next, jumper"
                        class="w-h-100"
                    />
                </div>
            </div>
            
            <div>
                <el-divider content-position="left">已选题目</el-divider>
                <el-table :data="chooseList" v-loading="chooseLoading" class="table-s is-chose" style="width: 100%" border>
                    <el-table-column min-width="80" :show-overflow-tooltip="true" label="题目排序"  align="center">
                        <template #default="scope">
                            <div><el-input class="inp-s" @focus="handleFocus(scope.row)" @blur="handleInput(scope.row)" type="number" v-model="scope.row.n_Sort" placeholder="请输入题目排序" /></div>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="80" :show-overflow-tooltip="true" label="考题类型"  align="center">
                        <template #default="scope">
                            <span v-if="scope.row.n_Type === 0" style="color: #409EFF;">{{scope.row.v_TypeName}}</span>
                            <span v-if="scope.row.n_Type === 1" style="color: #67C23A;">{{scope.row.v_TypeName}}</span>
                            <span v-if="scope.row.n_Type === 2" style="color: #E6A23C;">{{scope.row.v_TypeName}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="80" :show-overflow-tooltip="true" prop="n_Score" label="单题分数"  align="center" />
                    <el-table-column min-width="160" :show-overflow-tooltip="true" prop="v_Topic" label="题目"  align="center" />
                    <!-- <el-table-column min-width="60" label="操作" align="center" fixed="right">
                        <template #default="scope">
                            <div class="operate-s">
                                <el-button @click="deleteHandle(scope.row.id)" class="icon-e" icon="ele-Delete" size="small" text type="danger">移除</el-button>
                            </div>
                        </template>
                    </el-table-column> -->
                    <el-table-column min-width="80" :show-overflow-tooltip="true" prop="v_Topic" label="详情数据"  align="center">
                        <template #default="scope">
                            <el-popover placement="left" :width="600" trigger="click">
                                <template #reference>
                                    <el-button text type="primary">查看</el-button>
                                </template>
                                <el-table border :data="scope.row.options">
                                    <el-table-column min-width="60" prop="v_Option" :show-overflow-tooltip="true" label="选项"  align="center">
                                        <template #default="scoped">
                                            <span v-if="scoped.row.v_Option">{{scoped.row.v_Option}}</span>
                                            <span v-else>-</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column min-width="160" prop="v_Content" :show-overflow-tooltip="true" label="内容"  align="center" />
                                    <el-table-column min-width="100" :show-overflow-tooltip="true" label="是否为正确答案"  align="center">
                                        <template #default="scoped">
                                            <span v-if="scoped.row.isTrue" style="color: #67C23A;">是</span>
                                            <span v-else style="color: #E6A23C;">否</span>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-popover>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <!-- <el-button @click="testPaperClick">考卷预览</el-button> -->
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm()">一键生成考卷</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , Ref, computed , toRef , watchEffect, toRefs , toRaw , nextTick, onMounted , watch } from 'vue'
import { FormInstance, FormRules , ElMessage, ElMessageBox } from 'element-plus'
import getTableData from '/@/utils/getTableData';
import { OmsEduExaminationDBPage , OmsEduExaminationPaperAdd , OmsEduExaminationPaperUpdate } from '/@/api/centerControl/sms';
import { numberParseChina } from '/@/utils/hook';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {}
export default defineComponent( {
    name: 'SelectTopic',
    components: {},
    props: {
        selectDialog:{
            type: Boolean,
            default: false,
        },
        selectInfo: {
            type: String,
            default: ''
        },
        basicsInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const ruleFormRef = ref();

        const transferVal:any = ref(0) // 需要查询的值
        let choseNum = 0;

        const multipleTableRef: Ref = ref(null);
        const chooseList:any = ref([]);
        const chooseLoading = ref(false);
        const v_CourseName = ref('');

        let searchObj:any = reactive({
            l_TrainingPlanId: 0,
            n_Type: 0,
        });

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** sortFun 排序函数 */
        const sortFun = () => {
            let sortArr: any = [];
            if(chooseList.value.length !== 0){
                chooseList.value.map((i:any,ix:any) => {
                    i.n_Sort = ix + 1;
                    sortArr.push(i)
                });
                // 重新排序
                sortArr.sort((a:any, b:any) => Number(a.n_Sort) - Number(b.n_Sort));
                chooseList.value = sortArr;
            }
            chooseLoading.value = false;
        }

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({})

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick()
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            clearFun();
            state.repeatDis = false;
            ctx.emit('cancelSelectClick');
        }

        /*** clearFun 重置数据 */
        const clearFun = () => {
            searchObj.n_Type = 0;
            transferVal.value = 0; // 需要查询的值
            chooseList.value = [];
            chooseLoading.value = false;
        }

        /*** submitForm 提交事件 */
        const submitForm = async () => {
            state.repeatDis = true;
            let param: any = JSON.parse(props.basicsInfo)
            if(chooseList.value.length === 0){
                ElMessage({
                    type: 'error',
                    message: '请选择需要生成试卷的题目',
                });
                return
            }
            let foundArr: any = [];
            chooseList.value.map((i: any) => {
                let foundObj: any = {}
                foundObj.n_Sort = i.n_Sort;
                foundObj.L_ExaminationDBId = i.id;
                foundArr.push(foundObj);
            });
            param.customQuestions = foundArr;
            let res: any;
            try{
                if(JSON.parse(props.basicsInfo).examinationDBs){
                    res = await OmsEduExaminationPaperUpdate(param);
                }else{
                    res = await OmsEduExaminationPaperAdd(param);
                }
                if(res.success){
                    ctx.emit('selectUseClick');
                    state.repeatDis = false;
                    clearFun();
                }else{
                    state.repeatDis = false;
                }
            }catch(error){ state.repeatDis = false; }
        }

        /*** testPaperClick 考卷预览 */
        const testPaperClick = (row: any) => {}

        /*** 监听selectDialog的变化 */
        watch(() => props.selectDialog,(newVal) => {
            if(newVal){
                if(JSON.parse(props.basicsInfo).examinationDBs) chooseList.value = JSON.parse(props.basicsInfo).examinationDBs;
                v_CourseName.value = JSON.parse(props.basicsInfo).v_CourseName;
                searchObj.l_TrainingPlanId = JSON.parse(props.basicsInfo).l_TrainingPlanId;
            }
        })

        /*** selectDialog 响应弹窗的关闭  */
        const selectDialog = computed(() => {
            return props.selectDialog
        })
        
        /*** searchClick 查询按钮 */
        const searchClick = () => {
            if(transferVal.value !== '') searchObj.n_Type = transferVal.value;
        };

        /*** acquireChange 搜索下拉框选择的数据 ---- 传给接口数据 */
        const acquireChange = (val:any) => {
            transferVal.value = val;
            searchObj.n_Type = transferVal.value;
            choseNum = val;
        }

        let recordInx: any = '';
        /*** handleFocus 序号输入框获取焦点事件 */
        const handleFocus = (val: any) => {
            recordInx = Number(val.n_Sort);
        }

        /*** handleInput 监听用户更改序号 */
        const handleInput = (val:any) => {
            chooseLoading.value = true;
            let len = chooseList.value.length;
            if(val.n_Sort === ''){
                val.n_Sort = recordInx;
            }
            if(Number(val.n_Sort) > len){
                ElMessage({
                    type: 'error',
                    message: '序号不能大于当前数据的条数',
                    duration: 1500,
                    onClose: () => {
                        val.n_Sort = recordInx;
                    }
                })
            }else{
                chooseList.value = chooseList.value.map((i: any) => {
                    if (Number(val.n_Sort) === Number(i.n_Sort) && val.id !== i.id) {
                        return { ...i, n_Sort: recordInx };
                    } else {
                        return i;
                    }
                });
                // 重新排序
                chooseList.value.sort((a:any, b:any) => Number(a.n_Sort) - Number(b.n_Sort));
            }
            chooseLoading.value = false;
        }

        /*** deleteHandle 移除选题数据 */
        const deleteHandle = (val:any) => {
            ElMessageBox.confirm('请确定移除此条数据？','提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            .then(async() => {
                chooseList.value = chooseList.value.filter((item:any) => item.id !== val);
                // 重新排序
                if(chooseList.value.length !== 0){
                    chooseLoading.value = true;
                    sortFun();
                }
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            });
        }

        /*** handleSelectionChange 多选函数 */
        let examTypeOne: any = []; // 单选
        let examTypeTwo: any = []; // 多选
        let examTypeThree: any = []; // 判断
        let manualSelection = true;
        const handleSelectionChange = (val:any) => {
            if(manualSelection){
                if(transferVal.value === 0) examTypeOne = JSON.parse(JSON.stringify(val)); // 单选
                if(transferVal.value === 1) examTypeTwo = JSON.parse(JSON.stringify(val)); // 多选
                if(transferVal.value === 2) examTypeThree = JSON.parse(JSON.stringify(val)); // 判断

                chooseLoading.value = true;
                let getArr = [...examTypeOne,...examTypeTwo,...examTypeThree];
                console.log(getArr,'getArr')
                chooseList.value = getArr;
                sortFun();
            }
        }

        /*** 获取当前列表数据 */
        const { list , loading } = getTableData(OmsEduExaminationDBPage,{},searchObj);
        const listData = ref();
        watchEffect(() => {
            manualSelection = false;
            if(toRaw(list.value).length !== 0){
                listData.value = [];
                nextTick(() => {
                    console.log(toRaw(list.value),'list.value')
                    listData.value = toRaw(list.value);
                    checkBoxFun(choseNum , listData.value);
                });
            }
        });

        /*** 复选框数据回显 */
        const checkBoxFun = (val: any,list: any) => {
            if(!loading.value){
                if(val === 0 && examTypeOne.length !== 0 && list.length !== 0){
                    nextTick(() => {
                        let newArr = list.filter((row: any) => examTypeOne.some(({id}: {id: any}) => id === row.id));
                        if (newArr.length !== 0 && multipleTableRef.value) {
                            newArr.map((row: any) => {
                                multipleTableRef.value!.toggleRowSelection(row, true);
                            });
                        }
                    });
                }
                if(val === 1 && examTypeTwo.length !== 0){
                    nextTick(() => {
                        let newArr = list.filter((row: any) => examTypeTwo.some(({id}: {id: any}) => id === row.id));
                        if (newArr.length !== 0 && multipleTableRef.value) {
                            newArr.map((row: any) => {
                                multipleTableRef.value!.toggleRowSelection(row, true);
                            });
                        }
                    });
                }
                if(val === 2 && examTypeThree.length !== 0){
                    nextTick(() => {
                        let newArr = list.filter((row: any) => examTypeThree.some(({id}: {id: any}) => id === row.id));
                        if (newArr.length !== 0 && multipleTableRef.value) {
                            newArr.map((row: any) => {
                                multipleTableRef.value!.toggleRowSelection(row, true);
                            });
                        }
                    });
                }
                manualSelection = true;
            }
        }

        return {
            ...getTableData(OmsEduExaminationDBPage,{},searchObj),
            handleClose,
            submitForm,
            cancelUseClick,
            ruleFormRef,
            ...toRefs(state),
            selectDialog,
            rules,
            deleteHandle,
            listData,
            
            searchClick,
            transferVal,
            acquireChange,
            responsiblePle: [
                {label: '单选' , value: 0},
                {label: '多选' , value: 1},
                {label: '判断' , value: 2},
            ],
            multipleTableRef,
            handleSelectionChange,
            chooseList,
            chooseLoading,
            handleInput,
            handleFocus,
            testPaperClick,
            v_CourseName,
        }
    },
} )
</script>
<style scoped lang="scss">
.chose-tab , .is-chose{
    :deep(.el-scrollbar__wrap){
        max-height: 14vh;
    }
}
.inp-s{
    :deep(.el-input__inner){
        text-align: center;
    }
}
</style>